<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>所属科目：</label>
                <div class="table-query-input">
                    <category-select
                        :category-id.sync="queryData.categoryId"
                        :props="{}"
                    />
                </div>
            </div>
            <div class="search-item">
                <label>所属章节：</label>
                <div class="table-query-input">
                    <el-cascader
                        v-model="queryData.chapterId"
                        v-loading="chapterFlag"
                        :show-all-levels="false"
                        clearable
                        filterable
                        :props="{
                                value: 'id',
                                label: 'name',
                                checkStrictly: true
                            }"
                        :options="chapterData"
                        @change="(value) =>handleCascaderChange(queryData,'chapterId',value)"
                    ></el-cascader>
                </div>
            </div>
            <div class="search-item">
                <label>视频名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        placeholder="请输入视频名称"
                        clearable
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>阿里云视频id：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.aliyunVideoId"
                        placeholder="请输入阿里云视频id"
                        clearable
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="danger"
                plain
                style="margin-bottom: 2em"
                icon="el-icon-delete"
                :disabled="selectDisable"
                @click="
                    tableDelete(
                        '/kc/course/video/deletes',
                        {
                            ids: tableSelect
                        },
                        true
                    )
                "
            >批量删除
            </el-button>

        </div>

        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="videoId"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>

                <el-table-column
                    prop="coverURL"
                    label="封面"
                    width="250"
                    align="center"
                >
                    <template slot-scope="scope">
                        <img class="aliyun-video-cover-img" title="scope.row.title" :src="scope.row.coverImg" />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="视频标题"
                    width="400"
                    align="center"
                >
                    <template
                        slot-scope="scope"
                        v-loading="scope.row.opLoading"
                    >
                        <div
                            v-show="!scope.row.nameEdit"
                            @dblclick="scope.row.nameEdit = true"
                        >
                            {{ scope.row.name }}
                        </div>
                        <el-input
                            v-show="scope.row.nameEdit"
                            v-model="scope.row.name"
                            @blur="
                        nameEditSave(
                            '/kc/course/video/change-name',
                            scope.row
                        )
                    "
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="categoryName"
                    label="所属分类"
                    width="150"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    prop="chapterName"
                    label="所属章节"
                    width="150"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    prop="sort"
                    label="排序"
                    width="180">

                    <template
                        slot-scope="scope"
                        v-loading="scope.row.opLoading"
                    >
                        <div
                            v-show="!scope.row.sortEdit"
                            @dblclick="scope.row.sortEdit = true"
                        >
                            {{ scope.row.sort }}
                        </div>
                        <el-input
                            v-show="scope.row.sortEdit"
                            v-model="scope.row.sort"
                            @blur="
                            sortEditSave(
                                '/kc/course/video/change-sort',
                                scope.row
                            )
                        "
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"

                    align="center"
                >
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            size="mini"
                            type="text"
                            icon="el-icon-upload"
                            :loading="scope.row.opLoading"
                            @click="handoutUpload('资料上传', scope.row)"
                        >上传资料
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>

        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            custom-class="two-dialog"
            width="50%"
        >
            <div>

                <el-upload
                    class="upload-demo"
                    action=""
                    :on-change="uploadHandleChange"
                    :on-remove="fileHandleRemove"
                    :auto-upload="false"
                    >
                    <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="addHandout">添加</el-button>
                </el-upload>
                    <el-table
                        :data="fileData"
                        border
                        style="margin-top: 2em">
                        <el-table-column
                            fixed
                            prop="name"
                            label="文件名称"
                            width="250">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.name" type="text" ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="type"
                            label="格式"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="size"
                            label="大小(M)"
                            width="120">
                            <template slot-scope="scope">
                                {{(scope.row.size/1024/1024).toFixed(2)}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="status"
                            label="上传状态"
                            >
                            <template slot-scope="scope">
                                <k-tag :tag="uploadStatus[scope.row.uploadStatus]"></k-tag>
                                <label v-show="scope.row.percentage !== 0 && scope.row.percentage !== undefined ">{{scope.row.percentage}}%</label>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            width="200"
                            align="center"
                            fixed="right"
                        >
                            <template slot-scope="scope">
                                <el-button
                                    v-if="scope.row.uploadStatus === 'added'"
                                    :loading="scope.row.opLoading"
                                    class="danger"
                                    type="text"
                                    icon="el-icon-delete"
                                    size="mini"
                                    @click=" tableDelete(
                                    '/kc/course/video/handout/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true,
                                           (r)=>{
                                            removeFile(scope.$index);
                                           }

                                )"
                                >删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>



            </div>
        </el-dialog>
    </div>
</template>

<script>
import {TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {get, put, post} from "@/api/request";
import CategorySelect from "@/components/CategorySelect.vue";
import { ossUpload } from "@/utils/file";

export default {
    name: "AliyunVideoList",
    components: {CategorySelect},
    mixins: [TablePage],
    data() {
        let self = this;
        return {
            queryData: {
            },
            fileList: [],
            fileData: [],
            fileUpdateData: {}
        };
    },
    computed: {
        ...mapState({
            uploadStatus: state => state.status.uploadStatus,
        })
    },
    watch: {
        "queryData.categoryId"(categoryId) {
            if (!categoryId) {
                this.chapterData = [];
            } else {
                this.loadChapterTree(categoryId);
            }
        }
    },
    created() {
        this.loadCate({cateId:-1},(category) => {
            if (category !== null) {
                this.cateList = category
            }
        });
    },
    mounted() {
    },
    methods: {
        search(queryData)  {
            this.loadTable("/kc/course/video/page", queryData);
        },

        loadCate(queryData,callback)  {
            get("/kc/course/aliyun/video/cate", queryData).then(res => {
                callback(res.subCategories.category);
            });
        },
        handleCascaderChange(value) {
            if (Array.isArray(value) && value.length > 0) {
                // 将最后一级的值设置为 cateId
                this.queryData.cateId = value[value.length - 1];
            } else {
                this.queryData.cateId = -1;
            }
        },
        handoutUpload(title,row){
            this.fileData =[];
            this.dialogFormTitle = title;
            this.dialogFormVisible = true;
            this.fileUpdateData.videoId = row.id;

            get("/kc/course/video/handout/"+row.id).then(res => {
                this.fileData = res;
                if(this.fileData !== undefined || this.fileData.length > 0){
                    this.fileData.forEach(item => {
                        this.$set(item,"uploadStatus","added");
                    });
                }
            });

        },
        uploadHandleChange(file, fileList){
            this.fileData.push(
                {
                    uid: file.uid,
                    name: file.name,
                    size: file.size,
                    type: file.raw.type,
                    uploadStatus: "waitUpload",
                    raw: file.raw,
                    percentage: file.percentage,
                    url: "",
                }
            )
        },
        fileHandleRemove(file, fileList){
            this.fileData = this.fileData.filter(fileIndex => fileIndex.uid !== file.uid );
        },
        submitUpload(){
            this.fileData.forEach((file,index) => {
                if (file.uploadStatus === "waitUpload"){
                    ossUpload("cdn", file.name, file.raw, p => {
                        this.$set(this.fileData[index], "percentage", p * 100);
                        this.$set(this.fileData[index], "uploadStatus", "uploading");

                    }).then(result => {
                        this.$set(this.fileData[index], "url", result);
                        this.$set(this.fileData[index], "uploadStatus", "uploadSuccess");
                    });
                }
            });
        },
        addHandout(){
            if(this.fileData.filter(fileIndex => fileIndex.uploadStatus === "uploading" || fileIndex.uploadStatus === "waitUpload").length > 0){
                this.$message.error("请等待文件上传完成");
                return;
            }
            this.fileList = this.fileData.filter(fileIndex => fileIndex.uploadStatus === "uploadSuccess" );
            console.log("fileList",this.fileList);
            post("/kc/course/video/upload-handout", {
                videoId: this.fileUpdateData.videoId,
                videoHandoutModel: this.fileList
            }).then(res => {
                if (res){
                    this.$message.success("上传成功");
                    this.dialogFormVisible = false;
                }

            })
        },
        removeFile(index){
            this.fileData.splice(index, 1);
        }


    }
};
</script>

<style lang="scss" scoped>
.aliyun-video-cover-img{
    width: 200px;
}

</style>
